using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace KALE_Scanning
{
    public static class Extenstions
    {
        private static Dictionary<Type, Action<System.Windows.Forms.Control>> controldefaults = new Dictionary<Type, Action<System.Windows.Forms.Control>>()
        { 
                 {typeof(TextBox), c => ((TextBox)c).Clear()},
                 {typeof(RichTextBox), c => ((RichTextBox)c).Clear()},
                 {typeof(CheckBox), c => ((CheckBox)c).Checked = false},
                 {typeof(ListBox), c => ((ListBox)c).Items.Clear()},
                 {typeof(RadioButton), c => ((RadioButton)c).Checked = false},
                 {typeof(GroupBox), c => ((GroupBox)c).Controls.ClearControls()},
                 {typeof(CheckedListBox), c => ClearItem((CheckedListBox)c)},
                 {typeof(DateTimePicker), c => ((DateTimePicker)c).Value = DateTime.Now},
                 {typeof(ComboBox), c => ((ComboBox)c).SelectedItem = null},
                 {typeof(Panel), c => ((Panel)c).Controls.ClearControls()}
        };

        private static bool ClearItem(CheckedListBox lst)
        {
            for (int i = 0; i < lst.Items.Count; i++)
            {
                lst.SetItemChecked(i, false);
            }
            return true;
        }
        private static void FindAndInvoke(Type type, System.Windows.Forms.Control control)
        {
            if (controldefaults.ContainsKey(type))
            {
                controldefaults[type].Invoke(control);
            }
        }

        public static void ClearControls(this System.Windows.Forms.Control.ControlCollection controls)
        {
            foreach (System.Windows.Forms.Control control in controls)
            {
                FindAndInvoke(control.GetType(), control);
            }
        }

        public static void ClearControls<T>(this System.Windows.Forms.Control.ControlCollection controls) where T : class
        {
            if (!controldefaults.ContainsKey(typeof(T)))
                return;

            foreach (System.Windows.Forms.Control control in controls)
            {
                if (control.GetType().Equals(typeof(T)))
                {
                    FindAndInvoke(typeof(T), control);
                }
            }

        }

    }
}